<?php
namespace app\api\controller;
use app\api\controller\Base;
use think\Db;
use think\helper\Time;
use \WeChatPay\Builder;
use \WeChatPay\Crypto\Rsa;
use \WeChatPay\Util\PemUtil;
use \WeChatPay\Formatter;
class My extends Base
{
    public function _empty()
    {
        header("Location:/404.html");
        exit;
    }
    public function ajax()
    {
        $data=input('post.');
		if(!$data){
			header("Location:/404.html");
			exit;
		}
        $lizhili=Base::lizhili($data,true);
       if($lizhili['code']==0){
           return json(['code'=>10005,'message'=>'提交数据错误！']);
       }
        if($lizhili['code']===1){
            return ['code'=>10001,'message'=>'提交超时，请重复提交！'];
        }
        if($lizhili['code']===2){
            return ['code'=>10002,'message'=>'重复提交，请稍后重试！'];
        }
		if($lizhili['code']===3){
			return ['code'=>10000,'message'=>'token错误'];
		}
        $user=Db::name('user')->where('token',$data['token'])->field('openid_app,unionid,password,yzm,beizhu,token',true)->find();
		
		//核销
		if($data['type']=='update_tuan_order_hexiao'){
			$order=Db::name('order')->where('out_trade_no',$data['out_trade_no'])->where('lei',4)->where('hexiao',0)->find();
			if($order){
				Db::name('order')->where('id',$order['id'])->update([
					'hexiao'=>1,
					'hexiao_time'=>time(),
					'order_type'=>2
				]);
				return ['code'=>1,'message'=>'成功'];
			}else{
				return ['code'=>0,'message'=>'核销失败'];
			}
		}
		//获取团购订单 
		if($data['type']=='get_tuangou_order_list'){
			if($data['name']=='未核销'){
				$where=[
					['hexiao','=',0]
				];
			}
			if($data['name']=='已核销'){
				$where=[
					['hexiao','=',1]
				];
			}
			if($data['name']=='全部订单'){
				$where=true;
			}
			
			$list=Db::name('order')->where('lei',4)->where('tuan_id','>',0)->where('pay_status',1)->where($where)->page($data['page'],10)->order('order_time desc')->field('id,attr,beizhu,goods_id,goods_price,order_num,out_trade_no,phone,create_time,hexiao')->select();
			//dump(Db::getLastSql());
			foreach($list as $k=>$v){
				$goods=Db::name('goods')->where('id',$v['goods_id'])->field('id,goods_name,goods_img')->find();
				$list[$k]['goods_name']=$goods['goods_name'];
				$list[$k]['goods_img']=$goods['goods_img'];
			}
	
			
			if($list){
				return ['code'=>1,'message'=>'获取成功','data'=>$list];
			}else{
				if($data['page']==1){
					return ['code'=>2,'message'=>'无数据'];
				}
				return ['code'=>0,'message'=>'无数据'];
			}
		}
		//申请团购代理
		if($data['type']=='update_tuan_shen'){
			if(Db::name('tuan')->where('uid',$user['id'])->find()){
				return ['code'=>0,'message'=>'已经申请无需重复申请！'];
			}
			$data['create_time']=time();
			$data['update_time']=time();
			$data['uid']=$user['id'];
			$data['fid']=$user['fid'];
			Db::name('tuan')->strict(false)->insert($data);
			return ['code'=>1,'message'=>'成功'];
		}
		
	
        //设置团购地址
        if ($data['type']=='update_tuangou_one') {
            Db::name('user')->where('id',$user['id'])->update([
                'tuan_address'=>$data['id']
            ]);
            return ['code'=>1,'message'=>'成功'];
        }

		//获取团购列表
        if ($data['type']=='get_tuangou_list') {

            if(!$data['lat']){
                $data['lat']=38.03772;
            }
              if(!$data['lon']){
                  $data['lon']=114.53043;
              }
            $mall_config=Db::name('mall_config')->column('value','key');
            $url="https://apis.map.qq.com/ws/geocoder/v1/?location={$data['lat']},{$data['lon']}&key={$mall_config['txmap_key']}";
            $res=$this->curl($url);
          //  dump($res);
            if ($res['status']===0 and isset($res["result"]['ad_info']["district"]) and $res["result"]['ad_info']["district"]) {
                $address=$res["result"]['address'];

                $cha=$this->returnSquarePoint($data['lon'], $data['lat'],50);
                $where=[
                    ['lon','>',$cha["left_top"]["lng"]],
                    ['lon','<',$cha["right_top"]["lng"]],
                    ['lat','>',$cha["left_bottom"]["lat"]],
                    ['lat','<',$cha["right_top"]["lat"]],
                ];
                $res=Db::name('tuan')->where('lei',1)->where('uid','<>',0)->where('title','like','%'.$data['key'].'%')->where($where)->whereNull('delete_time')->select();
                foreach ($res as $k=>$v) {
                    $res[$k]['juli']=$this->getDistance($v['lon'], $v['lat'], $data['lon'], $data['lat']);
                }
                array_multisort(array_column($res, 'juli'), SORT_ASC, $res); //排序
                return ['code'=>1,'message'=>'成功','data'=>$res,'address'=>$address];
            } else {
                return ['code'=>0,'message'=>'获取定位失败'];
            }
        }
		//提交提现
		if ($data['type']=='update_my_ti') {
		   //提现日期
		   if(date('d')!=15){
			   return ['code'=>0,'message'=>'每月15日提现！'];
		   }
		   //登陆密码
		   if($user['password'] != md5(sha1($data['password']))){
			   return ['code'=>0,'message'=>'登陆密码错误'];
		   }
		   if(Db::name('ti')->where('uid',$user['id'])->where('type',1)->find()){
			   return ['code'=>0,'message'=>'提现正在审核中，不能重复提交！'];
		   }
		   if($data['money'] < 100){
		   		return ['code'=>0,'message'=>'最低提现金额为100元！'];
		   }
		   if($user['money'] < $data['money']){
		   		return ['code'=>0,'message'=>'账户余额不足！'];
		   }
		   Db::name('ti')->insert([
			   'uid'=>$user['id'],
			   'money'=>$data['money'],
			   'type'=>1,
			   'time'=>time(),
			   'name'=>$data['name'],
			   'phone'=>$data['phone'],
			   'order_id'=>time().$user['id'].mt_rand(1000,9999),
		   ]);
		   return ['code'=>1,'message'=>'成功'];
		}
		
		
		//获取钱列表
		if ($data['type']=='get_money_list') {
            if ($data=Db::name('money')->order('id desc')->where('uid',$user['id'])->page($data['page'],15)->select()) {
                return ['code'=>1,'message'=>'成功','data'=>$data];
            } else {
                return ['code'=>0,'message'=>'获取失败'];
            }
        }

        //点赞
        if ($data['type']=='get_arc_zan') {
            $info=Db::name('article')->where('id',$data['id'])->setInc('zan');
            if ($info) {
                return ['code'=>1,'message'=>'成功','data'=>$info];
            } else {
                return ['code'=>0,'message'=>'获取失败'];
            }
        }
        //留言
        if ($data['type']=='get_arc_hui_tj') {
            if(!$data['desc']){
                return ['code'=>0,'message'=>'留言内容不能为空'];
            }
            $info=Db::name('article_hui')->insert([
                'uid'=>$user['id'],
                'desc'=>$data['desc'],
                'time'=>time(),
                'aid'=>$data['id']
            ]);
            if ($info) {
                return ['code'=>1,'message'=>'成功'];
            } else {
                return ['code'=>0,'message'=>'获取失败'];
            }
        }
        //生成海报
        if ($data['type']=='get_my_info_haibao') {
            if($user=Db::name('user')->where('token',$data['token'])->field('openid_app,openid_wx,unionid,password,yzm,beizhu,token',true)->find()){
                if(!$user['erweima']){
                    $host=request()->header('host');
                    $filename='haibao/erweima/'.$user['id'].'.png';
                    $haibao=\erweima\Qrcode::draw('http://'.$host.'/xia/main?f_user_no='.$user['user_no'], $filename);
                    Db::name('user')->where('id',$user['id'])->update(['erweima'=>$haibao]);
                }
                return ['code'=>1,'message'=>'成功','data'=>$user];
            }else{
                return ['code'=>0,'message'=>'失败'];
            }
        }

        //确认收货
        if($data['type']=='update_order_shou'){
            if(Db::name("order")->where('out_trade_no',$data['out_trade_no'])->update(['order_type'=>2])){
                return ['code'=>1,'message'=>'成功'];
            }else{
                return ['code'=>0,'message'=>'失败'];
            }
        }
        //获取订单信息
        if($data['type']=='get_order_list'){
            //	[{id:0, name:'全部订单'},{id:1, name:'未付款'},{id:2, name:'待发货'},{id:3, name:'已发货'},{id:4, name:'已完成'}]
            //pay_status
            //post_status
            if(!isset($data['xiao'])){
                $data['xiao']=1; //1代表创业，2代表消费商城
            }
            $user=Db::name('user')->where('token',$data['token'])->find();
            $page=$data['page'];
            if($data['lei']==0){
                $map=[
                    //
                ];
            }elseif($data['lei']==1){
                $map=[
                    'o.pay_status'=>0,
                ];
            }elseif($data['lei']==2){
                $map=[
                    'o.pay_status'=>1,
                    'o.order_type'=>0
                ];
            }elseif($data['lei']==3){
                $map=[
                    'o.pay_status'=>1,
                    'o.order_type'=>1
                ];
            }elseif($data['lei']==4){
                $map=[
                    'o.pay_status'=>1,
                    'o.order_type'=>2
                ];
            }
            $res=Db::name('order')
                ->alias('o')
                ->where('user_id',$user['id'])
                //->where('lei',$data['xiao'])
                ->where('pay_status',1)
                ->where('payment','<',100)
                ->field('o.*')->where($map)->order('o.id desc')->page($page,6)->select();
            foreach($res as $k=>$v){
                $goods=Db::name('goods')->find($v['goods_id']);
                $res[$k]['goods_img']=$goods['goods_img'];
                $res[$k]['goods_name']=$goods['goods_name'];
                $res[$k]['shop_price']=$goods['money'];
            }
            if($res){
                return ['code'=>1,'message'=>'获取成功','data'=>$res];
            }else{
                return ['code'=>0,'message'=>'获取失败'];
            }
        }
        //查看下一级
        if($data['type']=='get_my_tui_info'){
            $user=Db::name('user')->where('token',$data['token'])->field('openid_app,openid_wx,unionid,password,yzm,beizhu,token',true)->find();
            $shang=Db::name('user')->where('id',$user['fid'])->find();
            if(!$shang){
                $shang=[
                    'phone'=>'',
                    'user_no'=>'',
                ];
            }
            $list=Db::name('user')->where('fid',$user['id'])->select();
            return ['code'=>1,'message'=>'成功','data'=>$list,'shang'=>$shang];
        }
        //生成订单
        if($data['type']=='update_pay_order'){
            // $h = date('H');
            // $i = date('i');
            // if($h>=23 or ($h==22 and $i >30)){
            //     return ['code'=>2,'message'=>'系统维护时间不能操作！'];
            // }
            $user=Db::name('user')->where('token',$data['token'])->find();
            if(!$user){
                return ['code'=>2,'message'=>'提交错误！'];
            }
             // if(!isset($data['password1']) or !$data['password1']){
             //     return ['code'=>2,'message'=>'请输入密码！'];
             // }

             // if(md5(sha1($data['password1']))!=$user['password']){
             //     return ['code'=>2,'message'=>'交易密码不正确，不能操作！'];
             // }

            $goods=Db::name('goods')->find($data['id']);
            Db::name('goods')->where('id',$goods['id'])->setInc('sales_num');
            $zong=$goods['money']*$data['num'];
            $ji=$goods['id'].time().\mt_rand(1111,9999).$user['id'];
            $info=[
                'out_trade_no'=>'zong_'.$ji,
                'user_id'=>$user['id'],
                'payment'=>$data['pay'], //五种支付方式
                'goods_price_zong'=>$zong,
                'goods_id'=>$goods['id'],
                'goods_price'=>$goods['money'],
                'order_num'=>$data['num'],
				'tuan_id'=>$user['tuan_address'],
                'phone'=>$user['phone'],
                'lei'=>$goods['lei'],
                'beizhu'=>$data['beizhu'],
                'attr'=>isset($data['attr']) ? $data['attr'] : '',
                'postage'=>$goods['postage'],
            ];
            if($goods['lei']==1){
                $info['address']=$user['address'];
                $info['sheng_html']=$user['sheng_html'];
            }
            if($goods['lei']==4){
                $tuan=Db::name('tuan')->where('id',$user['tuan_address'])->find();
                $info['address']=$tuan['address'];
                $info['sheng_html']=$tuan['title'];
            }

            $order=\model('order');
            $wo=$order->save($info);
            $order_id=$order->id;
            if($wo){
              //  return ['code'=>4,'message'=>'支付尚未开通'];
			  
			  $config=Db::name('mall_config')->column('value','key');
			  $merchantId = $config['wx_merchat_id'];
			  // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
			  $merchantPrivateKeyFilePath = file_get_contents(env('root_path').'zhengshu/apiclient_key.pem');
			  $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
			  // 「商户API证书」的「证书序列号」
			  $merchantCertificateSerial = $config['wx_zhengshu'];
			  // 从本地文件中加载「微信支付平台证书」，用来验证微信支付应答的签名
			  $platformCertificateFilePath = file_get_contents(env('root_path').'zhengshu/wechatpay.pem');
			  $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
			  // 从「微信支付平台证书」中获取「证书序列号」
			  $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
			  // 构造一个 APIv3 客户端实例
			  $instance = Builder::factory([
			      'mchid'      => $merchantId,
			      'serial'     => $merchantCertificateSerial,
			      'privateKey' => $merchantPrivateKeyInstance,
			      'certs'      => [
			          $platformCertificateSerial => $platformPublicKeyInstance,
			      ],
			  ]);
			  //dump($config['wx_xcx_notify_url']);
			    try {
			        $resp = $instance
			        ->chain('v3/pay/transactions/jsapi')
			        ->post(['json' => [
			            'mchid'        => $config['wx_merchat_id'],
			  		"out_trade_no"=> $ji,
			  		"appid"=> $config['wx_xcx_appid'],
			  		"description"=> "向商城付款",
			  		"notify_url"=> $config['wx_xcx_notify_url'],
			  		"amount"=> [
			  			"total"=> (int)($zong*100),
			  			//"total"=>1,
			  			"currency"=> "CNY"
			  		],
			  		"payer"=> [
			  			"openid"=> $user['openid_wx']
			  		]
			        ]]);
			        if( $resp->getStatusCode()==200){
			  		$wo=json_decode($resp->getBody(),true); //prepay_id
			  	   $params = [
			  	       'appId'     => $config['wx_xcx_appid'],
			  	       'timeStamp' => (string)Formatter::timestamp(),
			  	       'nonceStr'  => Formatter::nonce(),
			  	       'package'   => 'prepay_id='.$wo["prepay_id"],
			  	   ];
			  	   $params += ['paySign' => Rsa::sign(
			  	       Formatter::joinedByLineFeed(...array_values($params)),
			  	       $merchantPrivateKeyInstance
			  	   ), 'signType' => 'RSA'];
			  	   
			  	  // Db::name('user_gu')->where('id')
			  	   
			  	//   echo json_encode($params);
			  	   return ['code' => 1, 'message' => '微信支付成功','data'=>$params];
			     }
			    } catch (\Exception $e) {
			    //  return ['code' => 0, 'message' => '微信支付错误'];
			     
			        // 进行错误处理
			        echo $e->getMessage(), PHP_EOL;
			        if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
			            $r = $e->getResponse();
			            echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
			            echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
			        }
			        echo $e->getTraceAsString(), PHP_EOL;
			    }


               // return ['code'=>1,'message'=>'成功'];
            }else{
                return ['code'=>0,'message'=>'插入数据库失败'];
            }
        }
        //获取支付订单
        if($data['type']=='get_pay_show'){
            $user=Db::name('user')->where('token',$data['token'])->find();
            if($user['tuan_address']){
                $user['tuan']=Db::name('tuan')->where('id',$user['tuan_address'])->find();
            }

            $goods=Db::name('goods')->where('isopen',1)->find($data['id']);
            if($goods){
                return ['code'=>1,'message'=>'成功','data'=>$goods,'user'=>$user];
            }else{
                return ['code'=>0,'message'=>'失败'];
            }
        }
        //修改个人中心
        if ($data['type']=='update_my_info') {
            $info=json_decode($data['info'],true);
            if($user=Db::name('user')->where('token',$data['token'])->find()){
				$in=[
                    'name'=>$info['name'],
                    'gender'=>$data['gender'],
                    'address'=>$info['address'],
                    'sheng'=>$data['sheng'],
                    'shi'=>$data['shi'],
                    'xian'=>$data['xian'],
                    'sheng_html'=>$data['sheng_html'],
                ];
				if(isset($info['phone'])){
					$in['phone']=$info['phone'];
				}
                Db::name('user')->where('id',$user['id'])->update($in);
                return ['code'=>1,'message'=>'成功'];
            }else{
                return ['code'=>0,'message'=>'失败'];
            }
        }



        //查看是否有权限
        if ($data['type']=='get_my_info') {
            if($user){
                if($user['fid']){
                    $user['shang']=Db::name('user')->where('id',$user['fid'])->value('user_no');
                }
                if($user['tuan_address']){
                    $user['tuan']=Db::name('tuan')->where('id',$user['tuan_address'])->find();
                }
				$tuan=Db::name('tuan')->where('uid',$user['id'])->find();
				if($tuan){
					$user['is_tuan']=$tuan['lei'];
				}else{
					$user['is_tuan']=-1;
				}
				
                $mall_config=Db::name('mall_config')->where('id','in',[8,9,13,18])->column('value','key');
                return ['code'=>1,'message'=>'成功','data'=>$user,'mall_config'=>$mall_config];
            }else{
                return ['code'=>0,'message'=>'失败'];
            }
        }

        return ['code'=>0,'message'=>'非法获取'];
    }
    public function update()
    {
        $data=input('post.');
        if (!isset($data["lizhili"]) or !isset($data["type"]) or $data["lizhili"]!= "0d89b868429be6158ba1ebc0f7c073de") {
            header("Location:/404.html");
            exit;
        }

        //修改头像
        if ($data['type']=='update_my_img') {
            $file = request()->file('');
            if (isset($file['file'])) {
                $info = $file['file']->move('uploads_tou');
                $li=strtr($info->getSaveName(), " \ ", " / ");
                $key='/uploads_tou/'.$li;
                Db::name('user')->where('token', $data['token'])->update(['avatarUrl'=>$key]);
                return	['code'=>1,'data'=>$key];
            } else {
                return ['code'=>0,'message'=>'上传错误'];
            }
        }
        //默认上传文件
        if ($data['type']=='uploadCards') {
            $file = request()->file('');
            if (isset($file['file'])) {
                $info = $file['file']->move('uploadCards');
                $li=strtr($info->getSaveName(), " \ ", " / ");
                $key='/uploadCards/'.$li;
                return	['code'=>1,'data'=>$key];
            } else {
                return ['code'=>0,'message'=>'上传错误'];
            }
        }
        //gui-upload-imageso 组件使用
        if ($data['type']=='upload_images') {
            $file = request()->file('');
            if (isset($file['img'])) {
                $info = $file['img']->move('uploadImages');
                $li=strtr($info->getSaveName(), " \ ", " / ");
                $key='/uploadImages/'.$li;
                return	['code'=>1,'data'=>$key];
            } else {
                return ['code'=>0,'message'=>'上传错误'];
            }
        }
        return ['code'=>0,'message'=>'非法获取'];
    }

    private function returnSquarePoint($lng, $lat, $distance = 5)
    {
        $earthdata=6371;//地球半径，平均半径为6371km
        $dlng =  2 * asin(sin($distance / (2 * $earthdata)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);
        $dlat = $distance/$earthdata;
        $dlat = rad2deg($dlat);
        $arr=array(
            'left_top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
            'right_top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
            'left_bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
            'right_bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
        );
        return $arr;
    }
    /**
     * 计算两点地理坐标之间的距离
     * @param  Decimal $longitude1 起点经度
     * @param  Decimal $latitude1  起点纬度
     * @param  Decimal $longitude2 终点经度
     * @param  Decimal $latitude2  终点纬度
     * @param  Int     $unit       单位 1:米 2:公里
     * @param  Int     $decimal    精度 保留小数位数
     * @return Decimal
     */
    private function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2)
    {
        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;
        $radLat1 = $latitude1 * $PI / 180.0;
        $radLat2 = $latitude2 * $PI / 180.0;
        $radLng1 = $longitude1 * $PI / 180.0;
        $radLng2 = $longitude2 * $PI /180.0;

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $distance = 2 * asin(sqrt(pow(sin($a/2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2), 2)));
        $distance = $distance * $EARTH_RADIUS * 1000;

        if ($unit==2) {
            $distance = $distance / 1000;
        }
        return round($distance, $decimal);
    }


}
